#include "main.h"

#include <string>
#include <iostream>
#include <locale>
#include <locale.h>
#include <gtk/gtk.h>
#include "Ui.h"
#include "utils.h"
#include "LyricUi.h"
#include "LyricTool.h"
#include "kugou.h"
#include "lyric_log.h"

#ifndef _WIN32
#include <langinfo.h>
#else
#include <windows.h>
#endif


static ddb_gtkui_t *gtkui_plugin = NULL;
DB_functions_t *deadbeef = NULL;


// DeaDBeeF日志输出函数（注意：此函数接收的logstr已经是UTF-8编码，因为经过了internal_log_output的转换）
void deadbeef_log_output(const char* logstr) {
    if (!logstr) {
        return;
    }
    
    // 注意：logstr 已经在 internal_log_output 中被转换为UTF-8
    // 这里只需要确保传递给 deadbeef 的字符串是安全的
    if (deadbeef && deadbeef->log) {
        // 调用deadbeef日志接口（logstr已经是UTF-8）
        deadbeef->log("%s", logstr);
    } else {
        // 如果deadbeef不可用，回退到默认输出（logstr已经是UTF-8）
        default_log_output(logstr);
    }
}

static DB_misc_t plugin;
DB_plugin_action_t remove_action = {};
DB_playItem_t* last = NULL;
gint death_signal = 0;  // 与main.h中的extern声明匹配
gint loading_lyrics_flag = 0;  // 原子标志，防止多个加载线程同时运行

// 全局变量保存当前的面板引用（也是全局LyricWidget实例）
LyricWidget* g_lyric_widget = NULL;

static int lyricbar_disconnect() {
	// 设置死亡信号，通知所有线程停止
	g_atomic_int_set(&death_signal, 1);
	
	// 注销widget
	if (gtkui_plugin) {
		gtkui_plugin->w_unreg_widget(plugin.plugin.id);
		gtkui_plugin = NULL;
	}
	
	// 报告引用计数统计
	lyric_log_info("lyricbar_disconnect: plugin disconnecting");
	
	// 清理日志系统
	lyric_log_cleanup();
	
	return 0;
}

static int lyricbar_stop() {
	// 设置死亡信号
	g_atomic_int_set(&death_signal, 1);
	
	// 清理全局状态（g_lyric_widget会在disconnect时清理）
	gtkui_plugin = NULL;
	last = NULL;
	g_lyric_widget = NULL;
	
	return 0;
}

static void lyricbar_destroy(ddb_gtkui_widget_s* widget) {
	g_assert(widget != NULL);
	
	// 设置死亡信号，确保所有线程停止访问
	g_atomic_int_set(&death_signal, 1);
	
	// 获取widget对应的LyricWidget
	widget_lyricbar_t* lyricbar_widget = (widget_lyricbar_t*)widget;
	LyricWidget* lyric_widget = lyricbar_widget->lpLyricWidget;
	g_assert(lyric_widget != NULL);
	
	// 如果这是当前活动的widget，先清空全局引用
	if (g_lyric_widget == lyric_widget) {
		g_lyric_widget = NULL;
	}
	
	// 清理LyricWidget资源
	if (lyric_widget) {
		// 停止定时器并清理歌词组件
		clear_widget(lyric_widget);
		
		// 等待一小段时间确保所有线程退出
		g_usleep(100000); // 100ms
		
		// 安全地清理互斥量
		// 注意：GMutex没有initialized字段，但g_mutex_clear对未初始化的mutex是安全的
		g_mutex_clear(&lyric_widget->mutex);
		
		// 释放LyricWidget内存
		g_free(lyric_widget);
	}
}

// Implementations of missing functions
static int is_cached(const char* artist, const char* title) {
	// Placeholder implementation
	// In a real implementation, this would check if lyrics are cached
	return artist && title ? 1 : 0;
}

static void get_tags() {
	// Placeholder implementation
	// In a real implementation, this would get and process track tags
}

/**
 * @brief 输出当前系统的 locale 和编码环境信息
 */
static void log_locale_info() {
	const gchar* lang = g_getenv("LANG");
	const gchar* lc_all = g_getenv("LC_ALL");
	const gchar* lc_ctype = g_getenv("LC_CTYPE");
	const gchar* lc_messages = g_getenv("LC_MESSAGES");
	
	lyric_log_info("=== Locale Environment Information ===\n");
	lyric_log_info("LANG: %s\n", lang ? lang : "(not set)");
	lyric_log_info("LC_ALL: %s\n", lc_all ? lc_all : "(not set)");
	lyric_log_info("LC_CTYPE: %s\n", lc_ctype ? lc_ctype : "(not set)");
	lyric_log_info("LC_MESSAGES: %s\n", lc_messages ? lc_messages : "(not set)");
	
	// 获取当前设置的 locale
	const gchar* current_locale = setlocale(LC_ALL, NULL);
	lyric_log_info("Current locale (LC_ALL): %s\n", current_locale ? current_locale : "(null)");
	
	const gchar* ctype_locale = setlocale(LC_CTYPE, NULL);
	lyric_log_info("Current locale (LC_CTYPE): %s\n", ctype_locale ? ctype_locale : "(null)");
	
	// 获取文件系统编码
	const gchar* filesystem_charset = NULL;
	gboolean is_utf8 = g_get_charset(&filesystem_charset);
	lyric_log_info("File system charset: %s (UTF-8: %s)\n", 
	               filesystem_charset ? filesystem_charset : "(unknown)",
	               is_utf8 ? "yes" : "no");
	
#ifndef _WIN32
	// Linux 下获取代码集信息
	const gchar* codeset = nl_langinfo(CODESET);
	lyric_log_info("System codeset (nl_langinfo): %s\n", codeset ? codeset : "(unknown)");
	
	// 尝试获取其他 locale 信息
	const gchar* radixchar = nl_langinfo(RADIXCHAR);
	const gchar* thousands_sep = nl_langinfo(THOUSEP);
	lyric_log_info("Radix character: %s\n", radixchar ? radixchar : "(unknown)");
	lyric_log_info("Thousands separator: %s\n", thousands_sep ? thousands_sep : "(unknown)");
#else
	// Windows 下获取代码页
	lyric_log_info("Windows code page: CP%d\n", GetACP());
	lyric_log_info("Windows OEM code page: CP%d\n", GetOEMCP());
#endif
	
	// GLib 编码信息
	const gchar* glib_codeset = g_get_codeset();
	lyric_log_info("GLib codeset: %s\n", glib_codeset ? glib_codeset : "(unknown)");
	
	lyric_log_info("=== End of Locale Information ===\n");
}

static void update_lyrics_wrapper(void* data) {
	// 自动清除标志的RAII辅助
	struct AutoFlagClear {
		~AutoFlagClear() { g_atomic_int_set(&loading_lyrics_flag, 0); }
	} auto_clear;
	
	// 检查死亡信号
	if (g_atomic_int_get(&death_signal)) {
		lyric_log_debug("update_lyrics_wrapper: death signal set, exiting");
		return;
	}
	
	DB_playItem_t* track = (DB_playItem_t*)data;
	if (!track) {
		lyric_log_error("update_lyrics_wrapper: track is NULL");
		return;
	}
	
	// 检查deadbeef是否有效
	if (!deadbeef) {
		lyric_log_error("update_lyrics_wrapper: deadbeef is NULL");
		// 注意：deadbeef为NULL时不能调用pl_item_unref，会导致崩溃
		// 这种情况下track引用会泄漏，但总比崩溃好
		return;
	}
	
	// 检查是否有可用的歌词面板
	g_assert(g_lyric_widget != NULL);
	
	// 获取歌曲信息
	deadbeef->pl_lock();
	const char* artist_raw = deadbeef->pl_find_meta(track, "artist");
	const char* title_raw = deadbeef->pl_find_meta(track, "title");
	const char* location_raw = deadbeef->pl_find_meta(track, ":URI");
	
	deadbeef->pl_unlock();
	
	// 检查死亡信号
	if (g_atomic_int_get(&death_signal)) {
		// 确保deadbeef有效后再调用unref
		if (deadbeef) {
			deadbeef->pl_item_unref(track);
			lyric_log_debug("UNREF: update_lyrics_wrapper_death_signal track=%p", track);
		}
		return;
	}
	
	// 转换字符串编码为UTF-8（Linux下GTK需要UTF-8编码的字符串）
	// 注意：即使raw值为NULL或空，也进行转换，set_lyrics会统一处理空值判断
	gchar* artist = artist_raw ? convert_to_utf8(artist_raw) : NULL;
	gchar* title = title_raw ? convert_to_utf8(title_raw) : NULL;
	
	// 文件路径也需要转换编码（使用g_filename_to_utf8处理文件系统编码）
	gchar* location = NULL;
	gsize bytes_read = 0;
	gsize bytes_written = 0;
	GError* error = NULL;
	
	if (location_raw) {
#ifndef _WIN32
		// Linux下，尝试将文件路径转换为UTF-8
		// 首先尝试直接使用（如果已经是UTF-8）
		if (g_utf8_validate(location_raw, -1, NULL)) {
			lyric_log_debug("[Linux] location_raw is UTF-8");
			location = g_strdup(location_raw);
		} else {
			// 尝试使用g_filename_to_utf8（从文件系统编码转换）
			lyric_log_debug("[Linux] location_raw is Not UTF-8");
			lyric_log_info("[Linux] Converting location_raw from filesystem encoding to UTF-8");
			location = g_filename_to_utf8(location_raw, -1, &bytes_read, &bytes_written, &error);
			if (!location || error) {
				// 如果失败，尝试通用编码转换
				if (error) {
					lyric_log_info("[Linux] g_filename_to_utf8 failed: %s", error->message);
					g_error_free(error);
					error = NULL;
				}
				g_free(location);
				lyric_log_info("[Linux] Falling back to convert_to_utf8 for location");
				location = convert_to_utf8(location_raw);
			} else {
				lyric_log_info("[Linux] Successfully converted location: %zu bytes read, %zu bytes written", 
				               bytes_read, bytes_written);
			}
		}
#else
		// Windows下，通常已经是UTF-8或本地编码，直接转换
		location = convert_to_utf8(location_raw);
#endif
	}
	
	// 设置歌词内容（如果还没有设置或歌曲已改变）
	g_mutex_lock(&g_lyric_widget->mutex);
	bool need_load_lyrics = false;
	// 加强检查条件，确保所有字段都匹配才认为是同一首歌
	bool is_same_song = (title && g_lyric_widget->title[0] != '\0' && strcmp(g_lyric_widget->title, title) == 0) &&
	                    (artist && g_lyric_widget->artist[0] != '\0' && strcmp(g_lyric_widget->artist, artist) == 0) &&
	                    (location && g_lyric_widget->location[0] != '\0' && strcmp(g_lyric_widget->location, location) == 0);
	
	// 如果是同一首歌且已经有歌词，则不需要重新加载
	if (is_same_song && g_lyric_widget->lyrics != NULL && g_list_length(g_lyric_widget->lyrics) > 0) {
		need_load_lyrics = false;
		lyric_log_debug("update_lyrics_wrapper: same song with existing lyrics, skipping load");
	} else {
		// 否则需要加载歌词（包括新歌或没有歌词的情况）
		need_load_lyrics = true;
		lyric_log_debug("update_lyrics_wrapper: different song or no lyrics, need to load");
	}
	g_mutex_unlock(&g_lyric_widget->mutex);
	
	// 如果需要加载歌词，则设置新的歌词
	// 注意：set_lyrics内部会处理空值判断和UI线程调度，可以从任何线程安全调用
	if (need_load_lyrics) {
		// 增加全局播放计数器，表示切歌
		// 使用原子操作增加计数器
		g_assert(g_lyric_widget != NULL);
		gint new_sequence = get_next_sequence();
		lyric_log_debug("update_lyrics_wrapper: song sequence=%u, loading new lyrics for %s - %s", 
		                new_sequence, artist ? artist : "(null)", title ? title : "(null)");
		SetLyricsUIData* ui_data =  g_new0(SetLyricsUIData, 1);
		ui_data->widget = g_lyric_widget;
		g_strlcpy(ui_data->title, title ? title : "", sizeof(ui_data->title) - 1);
    	g_strlcpy(ui_data->artist, artist ? artist : "", sizeof(ui_data->artist) - 1);
    	g_strlcpy(ui_data->location, location ? location : "", sizeof(ui_data->location) - 1);
		ui_data->song_seq = new_sequence;
		set_lyrics(ui_data);
		// set_lyrics内部会复制字符串（在UI线程中使用），所以这里需要释放原始字符串
		g_free(artist);
		g_free(title);
		g_free(location);
	} else {
		lyric_log_debug("update_lyrics_wrapper: lyrics already loaded for %s - %s", artist ? artist : "(null)", title ? title : "(null)");
		// 不需要加载，释放字符串内存
		g_free(artist);
		g_free(title);
		g_free(location);
	}
	
	// 释放track引用
	if (deadbeef) {
		deadbeef->pl_item_unref(track);
		lyric_log_debug("UNREF: update_lyrics_wrapper_success track=%p", track);
	}
	
	lyric_log_debug("update_lyrics_wrapper: completed successfully");
	// AutoFlagClear析构时会自动清除标志
}

static int remove_from_cache_action(DB_plugin_action_t* plugin, ddb_action_context_t ctx) {
	if (ctx == DDB_ACTION_CTX_SELECTION) {
		deadbeef->pl_lock();
		ddb_playlist_t* playlist = deadbeef->plt_get_curr();
		if (playlist) {
			DB_playItem_t* current = deadbeef->plt_get_first(playlist, PL_MAIN);
			while (current) {
				if (deadbeef->pl_is_selected(current)) {
					const char* artist = deadbeef->pl_find_meta(current, "artist");
					const char* title = deadbeef->pl_find_meta(current, "title");
					if (is_cached(artist, title)) {
						//remove(cached_filename(artist, title).c_str());
					}
				}
				DB_playItem_t* next = deadbeef->pl_get_next(current, PL_MAIN);
				deadbeef->pl_unlock();
				deadbeef->pl_item_unref(current);
				lyric_log_debug("UNREF: remove_from_cache_action track=%p", current);
				current = next;
			}
			deadbeef->plt_unref(playlist);
		}
	}
	return 0;
}

static int message_handler(struct ddb_gtkui_widget_s* widget, uint32_t id, uintptr_t ctx, uint32_t xx, uint32_t yy) {
	// 检查死亡信号
	if (g_atomic_int_get(&death_signal)) {
		lyric_log_debug("message_handler: death signal set, ignoring event %d", id);
		return 0;
	}
	
	auto event = (ddb_event_track_t*)(ctx);
	lyric_log_debug("message_handler: received event %d", id);
	
	switch (id) {
	case DB_EV_CONFIGCHANGED:
		// 配置改变时重新获取标签
		lyric_log_debug("message_handler: config changed");
		get_tags();
		break;
		
	case DB_EV_TERMINATE:
		// DeaDBeeF关闭时设置死亡信号
		lyric_log_info("message_handler: terminate event received");
		g_atomic_int_set(&death_signal, 1);
		break;
		
	case DB_EV_PLUGINSLOADED:
		lyric_log_info("message_handler: plugins loaded");
		// 插件加载完成后，不需要特殊处理
		break;
		
	case DB_EV_SONGSTARTED:
	{
		lyric_log_info("message_handler: song started");
		
		// 检查死亡信号和widget有效性
		if (g_atomic_int_get(&death_signal)) {
			lyric_log_debug("message_handler: death signal set, ignoring song started");
			return 0;
		}
		
		g_assert(g_lyric_widget != NULL);
		
		// 验证event和track有效性
		if (!event) {
			lyric_log_error("message_handler: event is NULL");
			return 0;
		}
		
		if (!event->track) {
			lyric_log_error("message_handler: event->track is NULL");
			return 0;
		}
		
		if (event->track == last) {
			lyric_log_debug("message_handler: same track as last, ignoring");
			return 0;
		}
		
		if (deadbeef->pl_get_item_duration(event->track) <= 0.0) {
			lyric_log_warning("message_handler: track duration <= 0, ignoring");
			return 0;
		}
		
		lyric_log_debug("message_handler: processing new track");
		
		// 检查是否已有线程正在加载歌词，防止双击切歌时的并发问题
		// 使用原子比较和交换操作，确保原子性
		if (!g_atomic_int_compare_and_exchange(&loading_lyrics_flag, 0, 1)) {
			// 已有线程正在运行，无法获取锁
			lyric_log_debug("message_handler: another loading thread is running, skipping");
			return 0;
		}
		lyric_log_debug("message_handler: acquired loading lock");
		
		// 保存新的last指针（不增加引用计数，只是保存指针）
		if (last) {
			lyric_log_debug("message_handler: clearing last track");
		}
		last = event->track;
		
		// 为传递给线程的track增加引用计数（线程会unref一次）
		// 所以这里需要先ref一次
		deadbeef->pl_item_ref(event->track);
		lyric_log_debug("REF: message_handler_song_started track=%p", event->track);
		
		// 启动歌词更新线程
		lyric_log_debug("message_handler: starting update thread");
		auto tid = deadbeef->thread_start(update_lyrics_wrapper, event->track);
		if (tid) {
			deadbeef->thread_detach(tid);
			lyric_log_debug("message_handler: update thread started and detached");
		} else {
			lyric_log_error("message_handler: failed to start update thread");
			// 线程启动失败，需要unref之前在331行ref的track
			deadbeef->pl_item_unref(event->track);
			lyric_log_debug("UNREF: message_handler_thread_failed track=%p", event->track);
			// 清除标志
			g_atomic_int_set(&loading_lyrics_flag, 0);
		}
		break;
	}
	
	case DB_EV_PLAYBACK_STATE_DID_CHANGE:
		// 播放状态改变事件，通常不需要特殊处理
		lyric_log_debug("message_handler: playback state changed");
		break;
		
	case DB_EV_TRACKINFOCHANGED:
		// 轨道信息改变事件，通常不需要特殊处理
		lyric_log_debug("message_handler: track info changed");
		break;
		
	case DB_EV_CURSOR_MOVED:
		// 光标移动事件，通常不需要特殊处理
		lyric_log_debug("message_handler: cursor moved");
		break;
		
	case DB_EV_PLAYLISTCHANGED:
		// 播放列表改变事件，通常不需要特殊处理
		lyric_log_debug("message_handler: playlist changed");
		break;
		
	case DB_EV_PLAYLISTSWITCHED:
		// 播放列表切换事件，通常不需要特殊处理
		lyric_log_debug("message_handler: playlist switched");
		break;
		
	case DB_EV_SONGCHANGED:
		// 歌曲改变事件，通常不需要特殊处理
		lyric_log_debug("message_handler: song changed");
		break;
		
	case DB_EV_PAUSED:
		// 暂停事件，通常不需要特殊处理
		lyric_log_debug("message_handler: paused state changed");
		break;
		
	case DB_EV_NEXT:
		// 下一首事件，通常不需要特殊处理
		lyric_log_debug("message_handler: next track requested");
		break;
		
	case DB_EV_PREV:
		// 上一首事件，通常不需要特殊处理
		lyric_log_debug("message_handler: previous track requested");
		break;
		
	case DB_EV_PLAY_NUM:
		// 播放指定编号事件，通常不需要特殊处理
		lyric_log_debug("message_handler: play track number requested");
		break;
		
	case DB_EV_SONGFINISHED:
		// 歌曲结束事件，通常不需要特殊处理
		lyric_log_debug("message_handler: song finished");
		break;
		
	case DB_EV_STOP:
		// 停止事件，通常不需要特殊处理
		lyric_log_debug("message_handler: stop requested");
		break;
		
	case DB_EV_PAUSE:
		// 暂停事件，通常不需要特殊处理
		lyric_log_debug("message_handler: pause requested");
		break;
		
	case DB_EV_TOGGLE_PAUSE:
		// 切换暂停事件，通常不需要特殊处理
		lyric_log_debug("message_handler: toggle pause requested");
		break;
		
	default:
		lyric_log_debug("message_handler: unhandled event %d", id);
		break;
	}

	return 0;
}

static DB_plugin_action_t *lyricbar_get_actions(DB_playItem_t* playItem) {
	// 检查死亡信号
	if (g_atomic_int_get(&death_signal)) {
		remove_action.flags |= DB_ACTION_DISABLED;
		return &remove_action;
	}
	
	// 检查deadbeef是否有效
	if (!deadbeef) {
		remove_action.flags |= DB_ACTION_DISABLED;
		return &remove_action;
	}
	
	// 修复死锁：不持有外层锁，让每个函数自己管理锁
	// 这样可以避免 pl_get_first() 和 pl_is_selected() 内部加锁导致的死锁问题
	remove_action.flags |= DB_ACTION_DISABLED;
	
	// pl_get_first() 内部会自己加锁，不需要外层锁
	DB_playItem_t *current = deadbeef->pl_get_first(PL_MAIN);
	while (current) {
		// pl_is_selected() 和 pl_find_meta() 内部会自己管理锁，不需要外层锁
		if (deadbeef->pl_is_selected(current) && is_cached(
		            deadbeef->pl_find_meta(current, "artist"),
		            deadbeef->pl_find_meta(current, "title"))) {
			remove_action.flags &= (uint32_t)~DB_ACTION_DISABLED;
			deadbeef->pl_item_unref(current);
			// lyric_log_debug("UNREF: lyricbar_get_actions_found_cached track=%p", current);
			break;
		}
		// pl_get_next() 不需要锁，可以直接调用
		DB_playItem_t *next = deadbeef->pl_get_next(current, PL_MAIN);
		deadbeef->pl_item_unref(current);
		// lyric_log_debug("UNREF: lyricbar_get_actions_loop track=%p", current);
		current = next;
	}
	return &remove_action;
}

float get_position(gpointer user_data) {
	// 检查死亡信号
	if (g_atomic_int_get(&death_signal)) {
		return 0.0f;
	}
	
	// 检查deadbeef是否有效
	if (!deadbeef) {
		return 0.0f;
	}
	
	float pos = deadbeef->streamer_get_playpos();
	return pos;
}

gchar* get_track_location() {
	// 检查死亡信号和last track
	if (g_atomic_int_get(&death_signal) || !last || !deadbeef) {
		return NULL;
	}
	
	deadbeef->pl_lock();
	const char* track_location = deadbeef->pl_find_meta(last, ":URI");
	deadbeef->pl_unlock();
	
	if (!track_location) {
		return NULL;
	}
	
	return g_strdup(track_location);
}

static ddb_gtkui_widget_t *w_lyricbar_create(void) {
	// 创建widget结构体
	widget_lyricbar_t *widget = g_new0(widget_lyricbar_t, 1);
	if (!widget) {
		fprintf(stderr, "lyricbar: Failed to allocate widget memory\n");
		return NULL;
	}

	// 创建歌词组件
	LyricWidget* pLyricWidget = lyric_widget_new();
	if (!pLyricWidget) {
		fprintf(stderr, "lyricbar: Failed to create lyric widget\n");
		g_free(widget);
		return NULL;
	}

	// 设置位置获取回调函数
	pLyricWidget->get_position = get_position;
	
	// 连接右键菜单信号
	g_signal_connect(pLyricWidget->lyric_view, "populate-popup", G_CALLBACK(on_populate_popup), pLyricWidget);
	
	// 连接按钮事件，防止双击崩溃
	g_signal_connect(pLyricWidget->lyric_view, "button-press-event", G_CALLBACK(on_button_press_event), pLyricWidget);
	
	// 设置widget数据
	widget->lpLyricWidget = pLyricWidget;
	widget->base.type = "lyricbar";
	widget->base.widget = pLyricWidget->lyric_container;  // 使用container而不是view
	widget->base.destroy = lyricbar_destroy;
	widget->base.message = message_handler;

	// 设计模式支持（可选）
	if (gtkui_plugin && gtkui_plugin->w_override_signals) {
		gtkui_plugin->w_override_signals(widget->base.widget, widget);
	}

	// 确保小部件可见
	gtk_widget_show_all(widget->base.widget);
	
	// 保存全局面板引用（也是全局LyricWidget实例）
	g_lyric_widget = pLyricWidget;
	// 初始化全局计数器
	g_lyric_widget->global_sequence = 0;
	lyric_log_info("w_lyricbar_create: global lyric widget initialized, global_sequence=0");
	
	return (ddb_gtkui_widget_t*)widget;
}

int lyricbar_connect() {
	// 初始化日志系统（插件模式）
	// lyric_log_init(deadbeef_log_output, 1);
	lyric_log_init(deadbeef_log_output, 0, LYRIC_LOG_LEVEL_WARNING);

	// 输出 locale 信息
	log_locale_info();

	// 重置引用计数统计
	lyric_log_info("lyricbar_connect: reference count tracking initialized");
	
	// 获取GTK UI插件
	gtkui_plugin = (ddb_gtkui_t *)deadbeef->plug_get_for_id(DDB_GTKUI_PLUGIN_ID);
	if (!gtkui_plugin) {
		lyric_log_error("can't find gtkui plugin");
		return -1;
	}
	
	// 注册widget
	gtkui_plugin->w_reg_widget("Lyricbar", 0, w_lyricbar_create, "lyricbar", NULL);
	
	lyric_log_info("LyricBar plugin connected successfully");
	return 0;
}

#ifdef __cplusplus
extern "C" {
#endif

DDB_LYRICS_EXPORT DB_plugin_t *ddb_lyricbar_gtk3_load(DB_functions_t *ddb) {
	deadbeef = ddb;

	plugin.plugin.api_vmajor = 1;
	plugin.plugin.api_vminor = 5;
	plugin.plugin.version_major = 0;
	plugin.plugin.version_minor = 1;
	plugin.plugin.type = DB_PLUGIN_MISC;
	plugin.plugin.name = "Lyricbar";
	plugin.plugin.id = "lyricbar-gtk3";
	plugin.plugin.descr = "DeaDBeeF 音频播放器的歌词栏插件。\n为 DeaDBeeF 音频播放器获取并显示同步滚动歌词的插件。\n";
	plugin.plugin.copyright = "Copyleft (C) 2023 AsVHEn\n";
	plugin.plugin.website = "https://github.com/asvhen/deadbeef-lyricbar";
	plugin.plugin.connect = lyricbar_connect;
    plugin.plugin.stop = lyricbar_stop;
	plugin.plugin.disconnect = lyricbar_disconnect;
	plugin.plugin.get_actions = lyricbar_get_actions;
	plugin.plugin.configdialog =	"property \"字体缩放: \" hscale[0,10,0.01] lyricbar.fontscale 1; \n"
							"property \"结束URL搜索 (AZlyrics) (&x=...): \" entry lyricbar.end_url_search \"\"; \n"
							"property \"SP-DC Cookie (Spotify): \" entry lyricbar.sp_dc_cookie \"\"; \n";
	remove_action.name = "remove_lyrics";
	remove_action.flags = DB_ACTION_MULTIPLE_TRACKS | DB_ACTION_ADD_MENU;
	remove_action.callback2 = remove_from_cache_action;
	remove_action.next = NULL;
	remove_action.title = "从缓存中移除歌词";

	// bindtextdomain("deadbeef-lyricbar", "/usr/share/locale");
	// textdomain("deadbeef-lyricbar");

	return DB_PLUGIN(&plugin);
}

#ifdef __cplusplus
}
#endif
